import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/home_controller.dart';
import '../widgets/device_card.dart';
import '../widgets/weather_card.dart';
import '../../../../config/themes/app_colors.dart';
import '../../../routes/app_routes.dart';

/// 首页视图
class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('海隆HIOT云平台'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications_outlined),
            onPressed: () => controller.navigateToNotifications(),
          ),
        ],
      ),
      drawer: _buildDrawer(),
      body: Obx(() => _buildBody()),
      bottomNavigationBar: _buildBottomNavigationBar(),
      floatingActionButton: FloatingActionButton(
        onPressed: () => controller.addNewDevice(),
        child: const Icon(Icons.add),
      ),
    );
  }
  
  /// 构建抽屉菜单
  Widget _buildDrawer() {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          UserAccountsDrawerHeader(
            currentAccountPicture: CircleAvatar(
              backgroundColor: Colors.white,
              child: Text(
                controller.userInitials,
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            accountName: Text(controller.userName),
            accountEmail: Text(controller.userEmail),
          ),
          ListTile(
            leading: const Icon(Icons.home),
            title: const Text('首页'),
            onTap: () {
              Get.back();
              controller.changeBottomNavIndex(0);
            },
          ),
          ListTile(
            leading: const Icon(Icons.devices),
            title: const Text('设备管理'),
            onTap: () {
              Get.back();
              controller.changeBottomNavIndex(1);
            },
          ),
          ListTile(
            leading: const Icon(Icons.auto_awesome),
            title: const Text('场景管理'),
            onTap: () {
              Get.back();
              controller.changeBottomNavIndex(2);
            },
          ),
          ListTile(
            leading: const Icon(Icons.insert_chart_outlined),
            title: const Text('数据统计'),
            onTap: () {
              Get.back();
              controller.changeBottomNavIndex(3);
            },
          ),
          const Divider(),
          ListTile(
            leading: const Icon(Icons.settings),
            title: const Text('设置'),
            onTap: () => controller.navigateToSettings(),
          ),
          ListTile(
            leading: const Icon(Icons.help_outline),
            title: const Text('帮助与反馈'),
            onTap: () => controller.navigateToHelp(),
          ),
          ListTile(
            leading: const Icon(Icons.exit_to_app),
            title: const Text('退出登录'),
            onTap: () => controller.logout(),
          ),
        ],
      ),
    );
  }
  
  /// 构建正文内容
  Widget _buildBody() {
    // 根据当前选中的底部导航栏索引显示不同的页面
    switch (controller.selectedIndex) {
      case 0:
        return _buildDashboard();
      case 1:
        return _buildDevicesPage();
      case 2:
        return _buildScenesPage();
      case 3:
        return _buildStatsPage();
      default:
        return _buildDashboard();
    }
  }
  
  /// 构建仪表盘页面
  Widget _buildDashboard() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 欢迎消息
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '欢迎回来，${controller.userName}',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '上次登录: ${controller.lastLoginTime}',
                    style: const TextStyle(
                      color: Colors.grey,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 设备状态概览
          const Text(
            '设备状态概览',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Obx(() => GridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 2,
            childAspectRatio: 1.5,
            mainAxisSpacing: 10,
            crossAxisSpacing: 10,
            children: [
              _buildStatusCard('在线设备', controller.onlineDeviceCount.toString(), Colors.green),
              _buildStatusCard('离线设备', controller.offlineDeviceCount.toString(), Colors.grey),
              _buildStatusCard('告警设备', controller.alertDeviceCount.toString(), Colors.orange),
              _buildStatusCard('故障设备', controller.faultDeviceCount.toString(), Colors.red),
            ],
          )),
          
          const SizedBox(height: 16),
          
          // 最近活动
          const Text(
            '最近活动',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Obx(() => ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: controller.recentActivities.length,
            itemBuilder: (context, index) {
              final activity = controller.recentActivities[index];
              return ListTile(
                leading: Icon(activity['icon'] as IconData),
                title: Text(activity['title'] as String),
                subtitle: Text(activity['time'] as String),
                trailing: activity['isAlert'] as bool
                    ? const Icon(Icons.warning, color: Colors.orange)
                    : null,
              );
            },
          )),
        ],
      ),
    );
  }
  
  /// 构建设备页面
  Widget _buildDevicesPage() {
    return Obx(() => controller.isLoading
        ? const Center(child: CircularProgressIndicator())
        : controller.devices.isEmpty
            ? const Center(child: Text('暂无设备，点击右下角按钮添加设备'))
            : ListView.builder(
                padding: const EdgeInsets.all(10),
                itemCount: controller.devices.length,
                itemBuilder: (context, index) {
                  final device = controller.devices[index];
                  return Card(
                    margin: const EdgeInsets.only(bottom: 10),
                    child: ListTile(
                      leading: Icon(
                        controller.getDeviceIcon(device['type'] as String),
                        color: controller.getDeviceStatusColor(device['status'] as String),
                      ),
                      title: Text(device['name'] as String),
                      subtitle: Text(device['location'] as String),
                      trailing: Text(
                        device['status'] as String,
                        style: TextStyle(
                          color: controller.getDeviceStatusColor(device['status'] as String),
                        ),
                      ),
                      onTap: () => controller.openDeviceDetail(device['id'] as String),
                    ),
                  );
                },
              ));
  }
  
  /// 构建场景页面
  Widget _buildScenesPage() {
    return Obx(() => controller.isLoading
        ? const Center(child: CircularProgressIndicator())
        : controller.scenes.isEmpty
            ? const Center(child: Text('暂无场景，点击右下角按钮创建场景'))
            : GridView.builder(
                padding: const EdgeInsets.all(16),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 1.0,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemCount: controller.scenes.length,
                itemBuilder: (context, index) {
                  final scene = controller.scenes[index];
                  return Card(
                    child: InkWell(
                      onTap: () => controller.activateScene(scene['id'] as String),
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              controller.getSceneIcon(scene['type'] as String),
                              size: 48,
                              color: Theme.of(context).primaryColor,
                            ),
                            const SizedBox(height: 16),
                            Text(
                              scene['name'] as String,
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 16,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ));
  }
  
  /// 构建统计页面
  Widget _buildStatsPage() {
    return const Center(
      child: Text('数据统计页面正在开发中...'),
    );
  }
  
  /// 构建状态卡片
  Widget _buildStatusCard(String title, String value, Color color) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              value,
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: color,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  /// 构建底部导航栏
  Widget _buildBottomNavigationBar() {
    return Obx(() => BottomNavigationBar(
      currentIndex: controller.selectedIndex,
      onTap: controller.changeBottomNavIndex,
      type: BottomNavigationBarType.fixed,
      items: const [
        BottomNavigationBarItem(
          icon: Icon(Icons.dashboard),
          label: '首页',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.devices),
          label: '设备',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.auto_awesome),
          label: '场景',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.insert_chart_outlined),
          label: '统计',
        ),
      ],
    ));
  }
} 